<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="imgUrl" v-if="imgUrl" alt="" class="preview" />
      <img src="../../../assets/images/avatar.jpg" v-else alt="" class="preview" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" style="display:none" ref="inpFile" @change="chooseImg">
        <el-button type="primary" icon="el-icon-plus" @click="$refs.inpFile.click()" >选择图片</el-button>
        <el-button @click="uploadImg" type="success" icon="el-icon-upload" :disabled="imgUrl === ''" >上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data(){
    return {
      imgUrl:''
    }
  },
  methods:{
      async uploadImg(){
        const {data:res} = await this.$http.patch('/my/update/avatar',{avatar:this.imgUrl})
        if(res.code !==0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.imgUrl = ''
        this.$store.dispatch('user/initUserIfo')
      },
      chooseImg(e){
      const files = e.target.files
      if(files.length){
        //选择图片
        console.log(files[0]);
        const reader = new FileReader()
        reader.readAsDataURL(files[0])
        reader.addEventListener('load',()=>{
          this.imgUrl = reader.result
        })
      }else {
        //没有选择图片
        this.imgUrl=''
      }
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>